package com.itwn.portal.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itwn.common.constant.RedisConst;
import com.itwn.portal.model.entity.Book;
import com.itwn.portal.model.vo.CartVo;
import com.itwn.portal.service.BookService;
import com.itwn.portal.service.CartService;
import com.itwn.portal.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/cart")
@Api(tags = "购物车模块")
public class CartController {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CartService cartService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("查询购物车")
    @GetMapping
    public ResponseEntity<?> getCart(@RequestHeader("Authorization") String token) {
        // 获取用户id
        String userId = jwtUtil.getValue(token, "id");
        // 根据用户id查询购物车
        CartVo cartVo = cartService.getCart(Long.parseLong(userId));
        return ResponseEntity.ok(cartVo);
    }

    @ApiOperation("加入购物车")
    @PostMapping("/{bookId}")
    public ResponseEntity<?> addCart(
            @RequestHeader("Authorization") String token,@PathVariable("bookId")Long bookId) {
        
        // 获取用户id
        String userId = jwtUtil.getValue(token, "id");
        // 书籍加入购物车
        CartVo cartVo = cartService.addCart(Long.parseLong(userId),bookId);
        return ResponseEntity.ok(cartVo);
    }

    @ApiOperation("查询购买过的商品")
    @GetMapping("/buyDetail")
    public ResponseEntity<CartVo> buyDetail(
            @RequestHeader("Authorization") String token) {
        // 获取用户id
        String userId = jwtUtil.getValue(token, "id");
        // 从redis中获取购物车信息
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        CartVo cartVo = (CartVo) redisTemplate.opsForValue().get(key);
        return ResponseEntity.ok(cartVo);
    }
}
